<?php

/**
 * alltosun.com 用户接口 user.php
 * ============================================================================
 * 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 钱有明 (qianym@alltosun.com) $
 * $Date: 2015-7-3 上午9:42:33 $
 * $Id$
 */
class Action
{
    private $token = '';

    // 当前登录用户
    private $user_id = 0;

    // 当前登录用户详细信息
    private $user_info = array();

    public function __construct() {
        $this->token = an_request('token');

        if ($this->token) {
            $user_info = user_helper::get_user_info_by_token($this->token);
            if ($user_info && $user_info['status'] == 1) {
                $this->user_id = $user_info['id'];
                $this->user_info = $user_info;
                $this->user_info['avatar'] = user_helper::avatar($user_info['id']);
                $role_arr_list = user_config::$role_arr;
                $this->user_info['role_name'] = $role_arr_list[$user_info['role_type']];
            }
        }
    }

    /**
     * 用户登录
     */
    public function login_auth() {
        $user_name = an_request('user_name');
        $password = an_request('password');
        $device_id = an_request('device_id');
        // 登录类型，门店，合伙人
        $app_type = an_request('app_type');

        if (!$device_id) {
            //exit('wangdk');
            // api_helper::return_data(1, 'App未获取到设备ID');
        }

        // 验证接口
        $check_params = array(
            'user_name' => $user_name,
            'password' => $password,
            'device_id' => $device_id
        );
        $api_stat_id = api_helper::check_sign($check_params);

        $data = _widget('user')->login_auth($user_name, $password, $device_id, $app_type);
        if ($data[0]) {
            api_helper::return_data(0, 'success', $data[1]);
        } else {
            api_helper::return_data(1, $data[1]);
        }
    }

    /**
     * 取用户信息
     */
    public function get_user_info() {
        // 验证接口
        $api_stat_id = api_helper::check_sign(array());

        if (!$this->user_id) {
            api_helper::return_data(1, '该用户不存在');
        }

        $user_info = $this->user_info;
        if (!$user_info || $user_info['status'] == 0) {
            api_helper::return_data(1, '该用户不存在或已禁用');
        }
        $is_last_7day = dealers_helper::get_last_7day($this->user_id, 'init_stock');
        // 拼装返回数据
        $return_info = array(
            'avatar' => $user_info['avatar'],
            'bank_code' => $user_info['bank_code'],
            'bank_name' => $user_info['bank_name'],
            'user_name' => $user_info['user_name'],
            'mobile' => $user_info['mobile'],
            'qq' => $user_info['qq'],
            'weixin' => $user_info['weixin'],
            'realname' => $user_info['realname'],
            'role_name' => $user_info['role_name'],
            'store_house' => $user_info['store_house'],
            'is_last_7day_init_stock' => (string)$is_last_7day
        );
        api_helper::return_data(0, 'success', $return_info, $api_stat_id);
    }

    /**
     * 合伙人首页
     * http://192.168.2.246:8080/workspace/myWorkspace.action?projectId=1#65
     */
    public function agency_index() {
        $device_id = an_request('device_id');

        // 验证接口
        $api_stat_id = api_helper::check_sign(array(), 1);
        api_helper::get_user_info();

        if (!$this->user_id) {
            api_helper::return_data(1, '请先登录');
        }

        /*
        $store_id = Request::GetParam('store_id', 0);
        $store = store_helper::get_store($store_id);
        if (!$store) {
            api_helper::return_data(1, '店铺不存在');
        }
        */

        $filter = array();
        if ($this->user_info['role_type'] == user_config::AGENCY) {
            $user_id = $this->user_id;
        } else {
            api_helper::return_data(1, '身份不对');
        }

        $user_info = user_helper::get_user_info($user_id);

        // 更新用户的设备号
        if ($device_id) {
            // 来源
            $source = an_request('source');
            $source_list = api_config::$source;
            push_helper::save_user_reg_id($user_id, $device_id, $source_list[$source]);
        }

        //$marketing_info = _uri('user_marketing', array('marketing_id' => $user_id));

        $customer_num = stat_helper::get_customer_num(user_config::AGENCY, $user_id);

        $store_num = stat_helper::get_store_num(user_config::AGENCY, $user_id);

        $marketing_num = stat_helper::get_marketing_num($user_id);

        $unread_msg_num = message_center_helper::get_unread_message_num($user_id);
        // $unread_msg_num['noread_num'] = message_center_helper::get_unread_message_num($user_id);
        //$customer_num = stat_helper::get_todo_num(user_config::AGENCY, $user_id);

        /*
        $sale_money = 0;
        $stores = store_helper::get_marketing_stores($user_id);
        if (!empty($stores )){
            foreach ($stores as $store){
                $store_id = $store['id'];
                $sale_money = stat_helper::get_manager_month_purchase($store_id);
            }
        }
        */
        // $sale_arr = stat_helper::get_agency_month_sale($this->user_info['role_type'], $user_id);

        // $sale_arr_today = stat_helper::get_agency_daily_sale($this->user_info['role_type'], $user_id);

        // $sale_arr_yesterday = stat_helper::get_agency_yesterday_sale($this->user_info['role_type'], $user_id);

        $sale_num_month = _widget('stat.api_stat')->get_dealer_sale_data($this->user_info['id'], 'curr_month', 'box');
        $sale_money_month = _widget('stat.api_stat')->get_dealer_sale_data($this->user_info['id'], 'curr_month', 'price');

        $sale_num_today = _widget('stat.api_stat')->get_dealer_sale_data($this->user_info['id'], 'curr_day', 'box');
        $sale_money_today = _widget('stat.api_stat')->get_dealer_sale_data($this->user_info['id'], 'curr_day', 'price');

        $sale_num_yesterday = _widget('stat.api_stat')->get_dealer_sale_data($this->user_info['id'], 'prev_day', 'box');
        $sale_money_yesterday = _widget('stat.api_stat')->get_dealer_sale_data($this->user_info['id'], 'prev_day', 'price');

        $user_store = store_helper::get_user_store($user_id);
        // $store_id = @$user_store['user_id']; // todo
        //         $store_id = 1; // todo
        $stock_num = stat_helper::get_stock_num($user_store['id']);

        //发货订单
        //无法查询
        $no_deliver_num = stat_helper::get_agency_no_deliver_num($user_id);

        // 未处理的订单 @wangdk
        $unassigned_num = stat_helper::get_agency_unassigned_num($user_id);

        //xdq - 2 旗下所有影院门店欠款总额 未付款
        $unpayed_sum = stat_helper::count_agency_unpayed($user_id);

        // 商品种类数量
        $store_goods_category_num = goods_helper::get_store_goods_stock_category_num($user_store['id']);

        // 合伙人可进货商品种类数量
        $all_store_goods_category_num = goods_helper::get_all_store_goods_stock_category_num($user_store['id']);

        // 总的销售额
        $sale_money_all = _widget('stat.api_stat')->get_dealer_sale_data($this->user_info['id'], 'all', 'price');

        // 总销量
        $sale_num_all = _widget('stat.api_stat')->get_dealer_sale_data($this->user_info['id'], 'all', 'box');

        //库存管理 查询?
        //
        $trade_order_num = stat_helper::get_agency_trade_order_num($user_id);
        // 获取合伙人下的总店数

        // 获取合伙人默认仓库地址id
        $dealer_address_id = store_helper::get_dealer_address_id($user_id);
        if ($dealer_address_id) {
            $dealer_address_info = store_helper::get_dealer_address_info($user_id);
            if ($dealer_address_info) {
                $dealer_name = $dealer_address_info['dealer_name'];
                $dealer_mobile = $dealer_address_info['dealer_mobile'];
                $dealer_address = $dealer_address_info['dealer_address'];
            } else {
                $dealer_name = '';
                $dealer_mobile = '';
                $dealer_address = '';
            }
        } else {
            $dealer_name = '';
            $dealer_mobile = '';
            $dealer_address = '';
        }

        $ret = array(
            'user_id' => $user_id,
            'name' => $user_info['realname'] . ($user_info['user_money'] ? ' ' . $user_info['user_money'] . '元' : ''),
            'avatar' => $user_info['avatar'],
            //'department'           => $marketing_info['department'],
            //'job'                  => $marketing_info['job'],
            'area' => 'Todo',
            'dealer_address_id' => $dealer_address_id,
            'mobile' => $user_info['mobile'],
            // 电话
            'score' => $user_info['score'],
            // 积分数
            'bbcoin' => $user_info['bbcoin'],
            // 抱抱币
            'user_money' => $user_info['user_money'],
            // 用户余额
            // TODO bbcoin 是否开启使用抱抱币
            'is_bbcoin_enable' => bbcoin_helper::is_bbcoin_enable($user_id),
            // 是否开启抱抱币
            'store_house' => $dealer_address,
            // 合伙人默认的仓库地址
            'dealer_name' => $dealer_name,
            // 仓库收货人
            'dealer_mobile' => $dealer_mobile,
            // 仓库收货人手机号

            'customer_num' => $customer_num,
            //(总店)客户数
            'store_num' => $store_num,
            //终端/分店数
            'marketing_num' => $marketing_num,
            //市场人员数

            'unread_msg_num' => $unread_msg_num,
            //消息数
            'todo_num' => 0,
            //代办数

            // 任务数
            'job_num' => topic_helper::get_actived_job_num(array('agency_id' => user_helper::get_dealer_id_by_user_id($this->user_id))),

            'stock_num' => $stock_num,
            //库存数量
            'stock_money' => '0',
            //库存金额

            'no_deliver_num' => $no_deliver_num,
            //未发货订单数量
            'unassigned_num' => $unassigned_num,
            // 未处理的订单
            'trade_order_num' => $trade_order_num,
            //库存管理记录
            //             'goods_category_num'   => $goods_category_num, //库存商品种类数量

            'sale_money_month' => (string)$sale_money_month,
            // 本月销售金额
            'sale_num_month' => $sale_num_month,
            // 本月销售箱数

            'sale_num_today' => $sale_num_today,
            //今日销售数量
            'sale_money_today' => (string)$sale_money_today,
            //今日销售金额

            'sale_num_yesterday' => $sale_num_yesterday,
            //昨日销售数量
            'sale_money_yesterday' => (string)$sale_money_yesterday,
            //昨日销售金额
            'store_goods_category_num' => $store_goods_category_num,
            //库存商品种类数量
            'all_store_goods_category_num' => $all_store_goods_category_num,
            //库存商品种类总数量(包括库存是0的)
            'sale_money_all' => (string)$sale_money_all,
            // 总的销售额
            'sale_num_all' => $sale_num_all,
            'goods_baobaob_num' => order_config::$reward['bulk_bbcoin'],

            // 未付总额
            'unpayed_sum' => $unpayed_sum,
            //xdq add
            // 押金
            'deposit_money' => $user_info['deposit_money'],
            // 保证金
            'bargain_money' => $user_info['bargain_money'],

        );

        // 添加登陆记录
        user_helper::create_login_record($this->user_info);

        api_helper::return_data(0, 'success', $ret);
    }

    /**
     * 市场人员的首页
     */
    public function marketing_index() {
        $device_id = an_request('device_id');

        // 验证接口
        $api_stat_id = api_helper::check_sign(array(), 1);

        if (!$this->user_id) {
            api_helper::return_data(1, '请先登录');
        }

        $filter = array();
        if ($this->user_info['role_type'] == user_config::MARKETING) {
            //如果是市场人员身份
            $user_id = $this->user_id;
        } else {
            api_helper::return_data(1, '身份不对');
        }
        // error_log(json_encode($this->user_info));
        $user_info = user_helper::get_user_info($user_id);

        // 更新用户的设备号
        if ($device_id) {
            // 来源
            $source = an_request('source');
            $source_list = api_config::$source;
            push_helper::save_user_reg_id($user_id, $device_id, $source_list[$source]);
        }

        $marketing_info = _uri('user_marketing', array('marketing_id' => $user_id));

        //         $customer_num = stat_helper::get_customer_num(user_config::MARKETING, $user_id);
        $customer_num = store_helper::get_marketing_user_store_num($user_id);

        // $unread_msg_num = stat_helper::get_unread_msg_num($user_id);
        $unread_msg_num = message_center_helper::get_unread_message_num($user_id);

        //$customer_num = stat_helper::get_todo_num(user_config::AGENCY, $user_id);

        // $sale_arr = stat_helper::get_agency_month_sale($this->user_info['role_type'], $user_id);
        $sale_money = _widget('stat.api_stat')->get_marketing_sale_data($user_id, 'curr_month', 'price');
        $todo_num = order_helper::get_market_unprocess_order_num($user_id);

        // 获取父级合伙人id
        $dealer_id = $marketing_info['agency_id'];
        $dealer_user_info = user_helper::get_user_info($dealer_id);
        if ($dealer_user_info) {
            $dealer_mobile = $dealer_user_info['mobile'];
        } else {
            $dealer_mobile = '暂无';
        }


        $ret = array(
            'user_id' => $user_id,
            'name' => $user_info['realname'],
            'avatar' => $user_info['avatar'],
            'department' => $marketing_info['department'],
            'job' => $marketing_info['job'],
            'bbcoin' => $user_info['bbcoin'], // 抱抱币
            'area' => '中国',
            'dealer_mobile' => $dealer_mobile . '',
            'customer_num' => $customer_num . '', //客户数
            'unread_msg_num' => $unread_msg_num . '', //消息数
            'todo_num' => $todo_num, //代办数
            // 任务数
            'job_num' => topic_helper::get_actived_job_num(array('agency_id' => user_helper::get_dealer_id_by_user_id($this->user_id))),
            'sale_money' => (string)$sale_money, // 本月销售金额
            'sale_target' => $marketing_info['sale_target'] . '', // 本月销售任务
        );

        // 添加登陆记录
        user_helper::create_login_record($this->user_info);

        api_helper::return_data(0, 'success', $ret);
    }

    /**
     * 分店人员的 首页
     */
    public function manager_index() {
        // 验证接口
        $device_id = an_request('device_id');
        $store_id = Request::GetParam('store_id', 0);
        $check_params = array(
            'store_id' => $store_id
        );
        $api_stat_id = api_helper::check_sign($check_params, 1);

        api_helper::get_user_info();
        if (!$this->user_id) {
            api_helper::return_data(1, '请先登录');
        }

        $store = store_helper::get_store($store_id);
        if (!$store) {
            api_helper::return_data(1, '店铺不存在');
        }

        // 更新用户的设备号
        if ($device_id) {
            // 来源
            $source = an_request('source');
            $source_list = api_config::$source;
            push_helper::save_user_reg_id($this->user_id, $device_id, $source_list[$source]);
        }

        if ($this->user_info['role_type'] == user_config::STORE_OWNER) {
            // 如果是总店身份
            if ($store['owner_id'] != $this->user_id) {
                api_helper::return_data(1, '无权访问');
            }
        } elseif ($this->user_info['role_type'] == user_config::STORE_MANAGER) {
            //如果是分店是否
            if ($store['user_id'] != $this->user_id) {
                api_helper::return_data(1, '无权访问');
            }
        } else {
            api_helper::return_data(1, '身份不对');
        }

        $res = $this->get_store_common_sum_info(array($store['id']), array($store['user_id']));

        // 积分和店铺等级
        $level = 1;
        $level = score_record_helper::get_user_score_level($res['store_score']);

        $agency_user_info = user_helper::get_user_info($store['agency_id']);
        //获取门店市场人员的用户信息
        $marketing_user_info = user_helper::get_user_info($store['marketing_id']);

        $other_info = array(
            'agency_realname' => $agency_user_info['realname'],
            'agency_mobile' => $agency_user_info['mobile'], //合伙人手机号
            'agency_bank_name' => $agency_user_info['bank_name'], //合伙人银行
            'agency_bank_code' => $agency_user_info['bank_code'], //合伙人银行号
            'account_bank' => $agency_user_info['account_bank'], //开户行
            'marketing_realname' => $marketing_user_info['realname'], //市场人员姓名
            'marketing_mobile' => $marketing_user_info['mobile'], //市场人员手机号
            'store_level' => $level, //店铺等级
            'store_id' => $store['id'], //店铺ID
            'title' => $store['title'],
            'title_branch' => $store['title_branch'],
            'store_address' => $store['address'],
            'store_type' => $store['type'], //门店类型
            'is_allow_credit' => $store['is_allow_credit'],
            'store_status' => $store['status'], //店铺状态
            'goods_baobaob_num' => order_config::$reward['bulk_bbcoin'], //下单奖励
        );

        $res = array_merge($other_info, $res);
        // 添加登陆记录
        user_helper::create_login_record($this->user_info);

        api_helper::return_data(0, 'success', $res, $api_stat_id);
    }

    //总店首页
    public function main_store_index() {
        // 验证接口
        $device_id = an_request('device_id');
        $check_params = array();
        $api_stat_id = api_helper::check_sign($check_params, 1);

        api_helper::get_user_info();
        if (!$this->user_id) {
            api_helper::return_data(1, '请先登录');
        }

        // 更新用户的设备号
        if ($device_id) {
            // 来源
            $source = an_request('source');
            $source_list = api_config::$source;
            push_helper::save_user_reg_id($this->user_id, $device_id, $source_list[$source]);
        }

        $store_ids = array();
        $user_ids = array();

        $filter['owner_id'] = $this->user_id;
        $filter['status !='] = 0;
        $filter['is_delete'] = 1;
        $filter['is_enable'] = 1;
        $store_data = _model('store')->field('id', 'user_id')->getList(enable_filter($filter));
        $store_ids = array_column($store_data, 'id');
        $user_ids = array_column($store_data, 'user_id');

        $res = $this->get_store_common_sum_info($store_ids, $user_ids);
        $res = array_merge(array('store_num' => count($store_data)), $res);

        // 添加登陆记录
        user_helper::create_login_record($this->user_info);

        api_helper::return_data(0, 'success', $res, $api_stat_id);
    }

    private function get_store_common_sum_info($store_ids, $user_ids) {
        $goods_category_num = 0;
        $vocher_num = 0;
        $bbcoin_num = 0;
        $user_money_num = 0;
        $score = 0;

        //累计进货数
        $all_box_num = _widget('stat.api_stat')->get_store_sale_data($store_ids, 'all', 'box');
        //累计进货额度
        $all_money_num = _widget('stat.api_stat')->get_store_sale_data($store_ids, 'all', 'price');

        foreach ($store_ids as $k => $v) {
            $goods_category_num += stat_helper::get_manager_goods_category_num($v);
            //$vocher_num = store_verify_vocher_record_helper::get_store_verify_vocher_num($store['user_id']);
        }

        $user_list = _model('user')->field('user_money', 'bbcoin', 'score')->getList(array('id' => $user_ids));
        foreach ($user_list as $k => $v) {
            $bbcoin_num += $v['bbcoin'];
            $user_money_num += $v['user_money'];
            $score += $v['score'];
        }

        $device_num = store_helper::is_store_bind_device($store_ids);
        $deliver_order_num = order_helper::get_order_num_by_progress(array(5), $type = 5, array('store_id' => $store_ids));
        $receiver_order_num = order_helper::get_order_num_by_progress(array(10), $type = 5, array('store_id' => $store_ids));
        $cancel_order_num = order_helper::get_order_num_by_progress(array(15), $type = 5, array('store_id' => $store_ids));
        $all_order_num = order_helper::get_order_num_by_progress(array(1,3,5,10,15), $type = 5, array('store_id' => $store_ids));

        // 未读消息数
        $unread_msg_num = message_center_helper::get_unread_message_num($this->user_id);

        $ret = array(
            'purchase_num' => (string)$all_box_num, //累计进货总箱数
            'purchase_money' => format_money($all_money_num), //累计进货总金额
            'goods_category' => (string)$goods_category_num, //商品种类
            'vocher_num' => (string)$vocher_num, //核销数量
            'bbcoin' => format_money($bbcoin_num), //抱抱币
            'user_money' => format_money($user_money_num), //用户余额
            'unread_msg_num' => (string)$unread_msg_num, //消息数
            'store_score' => (string)$score, //积分数
            'is_bbcoin_enable' => bbcoin_helper::is_bbcoin_enable($this->user_id), //是否打开抱抱币
            'device_num' => $device_num, //设备数量
            'deliver_order_num' => $deliver_order_num, //配送中订单总数
            'receiver_order_num' => $receiver_order_num, //已收货订单总数
            'cancel_order_num' => $cancel_order_num, //撤销订单总数
            'all_order_num' => $all_order_num, //所有订单总数
            'store_half_year_order_data' => store_helper::get_half_year_order_by_store_id($store_ids), //近半年的进货金额与订单数量
        );

        return $ret;
    }

    //修改用户信息
    public function update_user_info() {
        $realname = an_request('realname');
        $mobile= an_request('mobile');
        $weixin = an_request('weixin');
        $password = an_request('password');
        $confirm_password = an_request('confirm_password');

        $check_params = array(
            'realname' => $realname,
            'mobile' => $mobile,
            'weixin' => $weixin,
            'password' => $password,
            'confirm_password' => $confirm_password
        );

        $this->validation_update_user_info($check_params);

        $api_stat_id = api_helper::check_sign($check_params, 1);

        $info = array(
            'realname' => $realname,
            'mobile' => $mobile,
            'weixin' => $weixin,
        );

        if ($password) {
            $new_password = user_helper::md5_password($password, $this->user_info['hash']);
            if ($this->user_info['password'] == $new_password) {
                api_helper::return_data(1, '不能和原密码一致');
            }
            $info = array_merge($info, array('password' => $new_password));
        }

        $res = _model('user')->update($this->user_id, $info);

        if ($res && $password) {
            $new_token = user_helper::create_token($this->user_id, $this->user_info['hash']);
            update_res_field('user', $this->user_id, array('token' => $new_token));
        }

        api_helper::return_data(0, 'success', array(), $api_stat_id);
    }

    private function validation_update_user_info($params) {
        if (!$params['realname']) {
            api_helper::return_data(1, '姓名必填');
        }
        if (!$params['mobile']) {
            api_helper::return_data(1, '手机号必填');
        }
        if (!preg_match('/^1[3|4|5|7|8]\d{9}$/', $params['mobile'])) {
            api_helper::return_data(1, '手机号格式不正确');
        }
        if ($params['password']) {
            if (!preg_match('/\d+/', $params['password'])) {
                api_helper::return_data(1, '密码必须为数字');
            }
            if ($params['password'] != $params['confirm_password']) {
                api_helper::return_data(1, '确认密码不正确');
            }
        }
    }

    /**
     * 找回密码
     */
    public function back_password() {
        $user_name = an_request('user_name');
        $app_type = an_request('app_type');

        // 验证接口
        $check_params = array(
            'user_name' => $user_name
        );

        $api_stat_id = api_helper::check_sign($check_params);

        $return_info = _widget('user')->send_code($user_name, $app_type);
        if ($return_info[0]) {
            api_helper::return_data(0, 'success', array(), $api_stat_id);
        } else {
            api_helper::return_data(1, $return_info[1]);
        }
    }

    /**
     * 重新下发密码
     */
    public function check_code() {
        $user_name = an_request('user_name');
        $code = an_request('code');

        // 验证接口
        $check_params = array(
            'user_name' => $user_name,
            'code' => $code
        );

        $api_stat_id = api_helper::check_sign($check_params);
        $return_info = _widget('user')->reset_password($user_name, $code);
        if ($return_info[0]) {
            api_helper::return_data(0, 'success', array());
        } else {
            api_helper::return_data(1, $return_info[1]);
        }
    }


}